package com.rm.zeyou.util.uploadUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author 🤙🤙🏼🤙🏽
 * @date 2024 8月 05 18:27
 * @Description
 */

@Slf4j
public class UploadUtils {
    private static final String UPLOAD_FOLDER = "/home/ruoyi/uploadPath/";

    public static String uploadFile(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return "上传失败：请选择文件";
        }
        try {
            byte[] bytes = file.getBytes();
            Path uploadPath = Paths.get(UPLOAD_FOLDER);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 使用UUID生成唯一文件名，防止文件覆盖
            String fileName = UUID.randomUUID() + "." + getFileExtension(file.getOriginalFilename());
            Path path = uploadPath.resolve(fileName);
            // 使用StandardCopyOption.REPLACE_EXISTING确保文件可以被替换（可选，根据需求决定）
            Files.write(path, bytes);
            return "http://192.124.176.47/img/" + path;
        } catch (IOException e) {
            // 使用日志记录异常，而不是打印堆栈跟踪（假设已有日志框架）
            log.error("文件上传失败", e);
            return "上传失败：发生IO异常";
        }
    }

    // 辅助方法，用于从原始文件名中提取文件扩展名
    private static String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return ""; // 如果没有扩展名，返回空字符串或默认扩展名
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
